package com.example.demo.Controller;

import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.config.AppConfig;
import com.example.demo.model.Article;
import com.example.demo.model.ArticleReply;
import com.example.demo.model.User;
import com.example.demo.services.IArticleReplyService;
import com.example.demo.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;

@Api("回复帖子")
@RequestMapping("/reply")
@Slf4j
@RestController
public class ArticleReplyController {
    @Autowired
    private IArticleReplyService articleReplyService;

    @Autowired
    private IArticleService articleService;


    @ApiOperation("回复帖子")
    @RequestMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @RequestParam(value = "articleId") @NonNull Long articleId,
                            @RequestParam(value = "content")  @NonNull String content) {
        // 获取用户信息
        request.getSession(false);
        User user=(User)request.getSession().getAttribute(AppConfig.USER_SESSION_KEY);

        //查看用户状态
        if(user.getState()!=0){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //获取文章
        Article article =articleService.selectById(articleId);
        if(article==null){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //文章状态
        if(article.getState()!=0){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        //创建回复
        ArticleReply articleReply=new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setPostUserId(user.getId());
        articleReply.setContent(content);
        articleReply.setReplyId(null);
        Date date=new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);

        //调用dao
        articleReplyService.create(articleReply);

        return AppResult.success();
    }

    @ApiOperation("获取帖子回复")
    @RequestMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId(Long articleId){
        if(articleId==null){
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        List<ArticleReply> articleReplies=articleReplyService.selectByArticleId(articleId);
        return AppResult.success(articleReplies);
    }
}
